package com.custom.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.custom.common.enums.RequestKey;
import com.custom.common.helper.ThreadCache;
import com.custom.common.util.JSONTools;
import com.custom.common.util.JWTVerifyUtils;
import com.custom.constants.GlobalConstant;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @ClassName:  RequestInterceptor   
 * @Description: 请求登录验证
 * @author: lizhen
 * @date:   2018年8月6日 上午9:15:38   
 *
 */
@Slf4j
@Component
public class RequestInterceptor implements HandlerInterceptor {

	/**
	 * jwt签名秘钥
	 */
	@Value("${jwtSecretKey}")
	public String jwtSecretKey;

	/**
	 * 方法调用前执行
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		response.setCharacterEncoding(GlobalConstant.PLATFORM_CHARACTER_ENCODING);
		response.setContentType(GlobalConstant.PLATFORM_RESPONSE_CONTENTTYPE_JSON);

		JSONObject requestMap = new JSONObject();
		String requestJSONStr = ThreadCache.getPostRequestParams();

		// 校验请求信息，是否为json格式
		if (!JSONTools.isJson(requestJSONStr)) {
			throw new Exception("不是json格式的参数请求");
		}

		// 字符串格式化为JSONObject
		requestMap = JSONObject.parseObject(requestJSONStr);
		// 校验请求json的必要属性(暂时只校验请求来源)

		// 请求token
		String admintoken = (String)requestMap.get(RequestKey.admintoken.name());
		if (StringUtils.isEmpty(admintoken)) {
			throw new Exception("参数为空");
		}

		// 解析Token，获取用户登录名
		String tokenSub = "";
		if(admintoken.startsWith("test")){
			tokenSub = admintoken.substring(4);
		}else {
			tokenSub = admintoken;
		}
		Claims claims = JWTVerifyUtils.verifyNotStartWithBearer(tokenSub,jwtSecretKey);
		// token验证失败
		if(claims == null){
			throw new Exception("无权限访问");
		}

		return true;
	}

	/**
	 * 方法调用执行
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
						   ModelAndView modelAndView) throws Exception {

	}

	/**
	 * 方法调用后执行，清除当前请求线程的本地请求的JSON数据
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
//		SystemContext.removeRequestJSON();
	}

}
